package com.example.mapper;


import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 *
 * @author aopmin
 * @since 2025/4/16
 */
@Slf4j
@RequiredArgsConstructor
@Repository // 标记当前bean为持久层组件
public class MongoDao {
    private final MongoTemplate mongoTemplate;

    /**
     * 保存数据
     * @param object
     */
    public String save(Object object) {
        log.info("save data to mongo. params:{} ", JSONUtil.toJsonStr(object));
        Assert.notNull(object, "入参不能为空");
        try {
            mongoTemplate.save(object);
            return "操作成功";
        } catch (Exception e) {
            log.error("save data to mongo error. params:{} reason:{}", JSONUtil.toJsonStr(object), e);
            return "操作失败";
        }
    }

    /**
     * 根据id查数据（MongoDB）
     *
     * @param id    数据唯一标识
     * @param clazz 实体类类型
     * @return 查询到的对象，未找到时返回null
     */
    public <T> T findById(String id, Class<T> clazz) {
        log.info("find data by id from mongo. id:{} ", id);
        Assert.notNull(id, "id字段不能为空");
        Assert.notNull(clazz, "类型不能为空");

        try {
            return mongoTemplate.findById(id, clazz);
        } catch (Exception e) {
            log.error("find data by id from mongo error. id:{} reason:{}", id, e.getMessage());
            return null; // 或者抛出自定义异常
        }
    }

    /**
     * 批量保存数据
     *
     * @param list 要保存的对象列表
     * @return 操作结果
     */
    public <T> String batchSave(List<T> list,String collectionName) {
        log.info("batch save data to mongo. params:{} ", JSONUtil.toJsonStr(list));
        Assert.notEmpty(list, "入参不能为空");
        try {
            // mongoTemplate.insertAll(list); // 不需要指定集合名称，它会自动识别实体类上@Document注解内容
            mongoTemplate.insert(list, collectionName);
            return "操作成功";
        } catch (Exception e) {
            log.error("batch save data to mongo error. params:{} reason:{}", JSONUtil.toJsonStr(list), e.getMessage());
            return "操作失败";
        }
    }

    /**
     * 条件查询
     * @param conditions
     * @return
     */
    public <T> List<com.example.demo.entity.Stu> findAllByClazzIdAndHobbies(Map<String,Object> conditions){
       Assert.notEmpty(conditions,"入参不能为空");
        Query query = new Query(); // 创建查询对象
        Optional<Map<String, Object>> optional = Optional.ofNullable(conditions);
        optional.ifPresent(map -> {
            map.forEach((k, v) -> {
                if (k.equals("clazzId")) {
                    // 等同于sql: where clazzId = v
                    query.addCriteria(Criteria.where("class_id").is(v));
                }
                if (k.equals("hobbies")) {
                    // 等同于sql: where hobbies in (v1,v2,v3)
                    if (v instanceof List) {
                        query.addCriteria(Criteria.where("hobbies").in((List<?>) v));
                    } else {
                        query.addCriteria(Criteria.where("hobbies").is(v));
                    }
                }
            });
        });
        try {
            return mongoTemplate.find(query, com.example.demo.entity.Stu.class);
        } catch (Exception e) {
            log.error("find data by id from mongo error. id:{} reason:{}", conditions, e.getMessage());
        }
        return null;
    }
}